package com.joelaws.prototype.server.blackberry;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.joelaws.prototype.server.MeetingService;

public class MeetUser extends Resource {

	private long thisUser;

	private long otherUser;

	private String action;

	public MeetUser(Context context, Request request, Response response) {
		super(context, request, response);
		String[] data = request.getResourceRef().getRemainingPart().split(":");

		thisUser = Long.MIN_VALUE;
		otherUser = Long.MIN_VALUE;
		if (data != null && data.length == 3) {
			String[] user;

			user = data[0].split("=");
			if (user != null && user.length == 2) {
				thisUser = Long.parseLong(user[1]);
			}

			user = data[1].split("=");
			if (user != null && user.length == 2) {
				otherUser = Long.parseLong(user[1]);
			}

			user = data[2].split("=");
			if (user != null && user.length == 2) {
				action = user[1];
			} else {
				action = null;
			}
		}

		super.getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}

	@Override
	public Representation getRepresentation(Variant variant) {
		if (thisUser == Long.MIN_VALUE || otherUser == Long.MIN_VALUE) {
			return new StringRepresentation("Invalid userID or action",
					MediaType.TEXT_PLAIN);
		}

		String info;
		try {
			if (action == null || action.length() == 0) {
				info = MeetingService.getService().initiateMeeting(thisUser,
						otherUser).toString();
			} else {
				info = MeetingService.getService().executeAction(thisUser,
						otherUser, action).toString();
			}
		} catch (Exception e1) {
			try {
				info = MeetingService.getService().getNextAction(thisUser,
						otherUser).toString();
			} catch (Exception e2) {
				info = "A meeting must first be requested";
			}
		}
		System.out.println("Meeting: " + info);
		Representation representation = new StringRepresentation(info,
				MediaType.TEXT_PLAIN);
		return representation;
	}

	public static String getURL() {
		return "/meet";
	}
}
